import React, { useEffect, useState } from 'react';
import { Card, List, Spin, message } from 'antd';
import { getAllProblem } from '@/services/problem';
import type { Problem, ResultVOListProblem } from '@/types/openapi';
import { history } from '@umijs/max';

const Home: React.FC = () => {
  const [problems, setProblems] = useState<Problem[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchProblems = async () => {
    try {
      const res: ResultVOListProblem = await getAllProblem();
      if (res.code === 200) {
        setProblems(res.data || []);
      } else {
        message.error(res.message || '获取题目失败');
      }
    } catch (err) {
      message.error('请求失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchProblems();
  }, []);

  return (
    <Card title="题库列表">
      {loading ? (
        <Spin />
      ) : (
        <List
          dataSource={problems}
          renderItem={(item) => (
            <List.Item
              style={{ cursor: 'pointer' }}
              onClick={() => history.push(`/problem/${item.problemId}`)}
            >
              <List.Item.Meta
                title={
                  <span>
                    <b>{item.problemId}.</b> {item.problemTitle}
                  </span>
                }
                description={`时间限制: ${item.timeLimit} / 内存限制: ${item.memLimit}`}
              />
            </List.Item>
          )}
        />
      )}
    </Card>
  );
};

export default Home;
